<!--
/**
* @author xuyh0817
* @email xuyh0817@foxmail.com
* @date 2022-03-27 22:58
* @version 2.0.0
* @doc todo
* @website todo
* @remark  如果要分发源码，需在本文件顶部保留此文件头信息！！
*/
-->
<template>
  <a-modal
    title="代码"
    :visible="visible"
    :footer="null"
    centered
    width="90%"
    @cancel="$emit('update:visible',false)"
  >
    <prism-editor
      v-model="code"
      class="x-render-code"
      :highlight="highlighter"
      line-numbers
    />
    <div style="text-align:center;margin-top: 20px;">
      <a-button type="primary" style="margin: 0 8px" @click="copyDataHandler">复制代码</a-button>
      <a-button type="primary" style="margin: 0 8px" @click="downloadDataHandler">下载文件</a-button>
      <a-button @click="$emit('update:visible', false)">关闭弹窗</a-button>
    </div>
  </a-modal>
</template>

<script>
import copy from 'clipboard-copy'

import {PrismEditor} from 'vue-prism-editor'
import {highlight, languages} from 'prismjs/components/prism-core'
import 'vue-prism-editor/dist/prismeditor.min.css'
import 'prismjs/themes/prism-tomorrow.css'
import AntTableTpl from '../tpl/antTable'

import { debounce } from 'lodash'

export default {
  name:'XRenderCodeDialog',
  inject: ['xDesignTable'],
  components: {
    PrismEditor
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      code: '',
      fileURL: ''
    }
  },
  watch: {
    // 当 showType 变化
    showType() {
      this.setCode()
    },
    // 当 visible 变化时
    visible(val) {
      if (val) {
        this.setCode()
      }
    },
    // 检测 code 当代码变化时，重新生成 URL
    code() {
      // 防抖，最后一次起作用
      if (!this.codeToURL) {
        this.codeToURL = debounce(() => {
          // 将代码转为 URL
          const blob = new Blob([this.code], {
            type: 'text/plain'
          })
          this.fileURL = URL.createObjectURL(blob)
        }, 200)
      }

      this.codeToURL()
    }
  },
  methods: {
    // 设置代码
    setCode() {
      const {xDesignTable} = this
      const tpl = AntTableTpl
      const {dataSourceUrl} = xDesignTable.tablePropsData
      this.code = tpl(
        JSON.stringify(xDesignTable.getTableConfig()), dataSourceUrl || 'http://'
      )
    },
    // 高亮代码
    highlighter(code) {
      return highlight(code, languages.js)
    },
    // 复制代码
    copyDataHandler() {
      const {code} = this
      copy(code)
      this.$message.success('复制成功!')
    },
    downloadDataHandler() {
      const {fileURL} = this
      const elink = document.createElement('a')
      elink.download = Date.now() + '.vue'
      elink.style.display = 'none'
      elink.href = fileURL
      document.body.appendChild(elink)
      elink.click()
      // 释放URL 对象
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
      this.$message.success('下载成功!')
    }
  }
}
</script>
<style lang="css" scoped>
.x-render-code {
  max-height: calc(80vh - 50px);
}
</style>
